// 重写登录
import { login, getInfo } from '@/api/user.js'
import { getUserDetailById } from '@/api/employees.js'
import { resetRouter } from '@/router'
import {
	getToken,
	setToken,
	removeToken,
	setTokenTime
} from '@/utils/auth.js'
const state = {
	token: getToken(),
	userInfo: {}
}
const mutations = {
	setToken(state, token) {
		state.token = token
		setToken(token)
	},
	removeToekn(state) {
		state.token = null
		removeToken()
	},
	/* 保存用户信息 */
	setUserInfo(state, infoData) {
		// state.userInfo = infoData
		state.userInfo = {
			...infoData
		} // 用浅拷贝的方式去赋值对象 因为这样数据更新之后，才会触发组件的更新
	},
	/* 移除用户信息*/
	reomveUserInfo(state) {
		state.userInfo = {}
	}

}
const actions = {
	/* 登录 */
	async login({ commit }, data) {
		const result = await login(data)
		console.log(result)
		if (result) {
			commit('setToken', result)
			setTokenTime()
		}
	},
	/* 获取保存用户信息 */
	async getInfo({ commit }) {
		const userinfo = await getInfo()
		const baseinfo = await getUserDetailById(userinfo.userId)
		const baseRes = { ...userinfo, ...baseinfo }	// 合并数据
		commit('setUserInfo', baseRes)
		return baseRes
	},

	async logout({ commit }) {
		commit('removeToekn')
		commit('reomveUserInfo')
		resetRouter()
		// vuex中 user子模块  permission子模块
		// 子模块调用子模块的mutation  默认情况下 子模块的context是子模块的
		commit('Permission/setRoutes', [], { root: true })
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}
